<template>
  <el-drawer v-model="formCtrl.isDrawerOpen" class="cupk2-data-form" :append-to-body="true" :with-header="false" size="500px">
    <div class="title">{{ currentFormType.type.title }}数据</div>
    <el-form :show-message="formCtrl.isShowValidMsg" v-loading="isLoading" :model="form" label-width="auto" ref="ruleFormRef" :disabled="!formCtrl.isAbledForm">
          <el-form-item label="主鍵:" prop="id" v-if="isShowform.id" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.id" />
      </el-form-item>
      <el-form-item label="标题：" prop="title" v-if="isShowform.title" :rules="v.getRules(true, 0, 128)">
        <el-input v-model="form.title" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="摘要：" prop="docdescribe" v-if="isShowform.docdescribe" :rules="v.getRules(false, 0, 512)">
        <el-input v-model="form.docdescribe" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="知识模型：" prop="knowmodel" v-if="isShowform.knowmodel" :rules="v.getRules(false)">
        <el-select v-model="form.knowmodel" placeholder="请选择">
          <el-option label="~" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="原作者:" prop="author" v-if="isShowform.author" :rules="v.getRules(false, 0, 32)">
        <el-input v-model="form.author" />
      </el-form-item>
      <el-form-item label="发布时间:" prop="pubtime" v-if="isShowform.pubtime" :rules="v.getRules(true, 0, 7)">
        <el-input v-model="form.pubtime" />
      </el-form-item>
      <el-form-item label="知识来源：" prop="source" v-if="isShowform.source" :rules="v.getRules(false, 0, 256)">
        <el-input v-model="form.source" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="状态：" prop="state" v-if="isShowform.state" :rules="v.getRules(true)">
        <el-select v-model="form.state" placeholder="请选择">
          <el-option label="~" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间:" prop="ctime" v-if="isShowform.ctime" :rules="v.getRules(true, 0, 8)">
        <el-input v-model="form.ctime" />
      </el-form-item>
      <el-form-item label="修改时间:" prop="etime" v-if="isShowform.etime" :rules="v.getRules(true, 0, 8)">
        <el-input v-model="form.etime" />
      </el-form-item>
      <el-form-item label="创建人姓名:" prop="cusername" v-if="isShowform.cusername" :rules="v.getRules(true, 0, 32)">
        <el-input v-model="form.cusername" />
      </el-form-item>
      <el-form-item label="创建人关键字:" prop="cuserkey" v-if="isShowform.cuserkey" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.cuserkey" />
      </el-form-item>
      <el-form-item label="修改人姓名:" prop="eusername" v-if="isShowform.eusername" :rules="v.getRules(true, 0, 32)">
        <el-input v-model="form.eusername" />
      </el-form-item>
      <el-form-item label="修改人关键字:" prop="euserkey" v-if="isShowform.euserkey" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.euserkey" />
      </el-form-item>
      <el-form-item label="备注：" prop="pcontent" v-if="isShowform.pcontent" :rules="v.getRules(false, 0, 64)">
        <el-input v-model="form.pcontent" autosize type="textarea" />
      </el-form-item>
      <el-form-item label="统计信息ID:" prop="runinfoid" v-if="isShowform.runinfoid" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.runinfoid" />
      </el-form-item>
      <el-form-item label="同步关键字:" prop="syncid" v-if="isShowform.syncid" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.syncid" />
      </el-form-item>
      <el-form-item label="版本ID:" prop="versionid" v-if="isShowform.versionid" :rules="v.getRules(true, 0, 16)">
        <el-input v-model="form.versionid" />
      </el-form-item>
      <el-form-item label="查询号:" prop="sno" v-if="isShowform.sno" :rules="v.getRules(false)">
        <el-input-number v-model="form.sno" />
      </el-form-item>
      <el-form-item label="有效期开始:" prop="validitys" v-if="isShowform.validitys" :rules="v.getRules(false, 0, 7)">
        <el-input v-model="form.validitys" />
      </el-form-item>
      <el-form-item label="有效期结束:" prop="validitye" v-if="isShowform.validitye" :rules="v.getRules(false, 0, 7)">
        <el-input v-model="form.validitye" />
      </el-form-item>
      <el-form-item>
        <el-row class="cupk2-form-button">
          <el-col :span="14">
            <el-button v-if="formCtrl.isShowSubmit" type="primary" @click="onSubmitForm(addData)">提交{{ currentFormType.type.title }}</el-button>
            <el-switch v-if="formCtrl.isShowRetain" v-model="isRetainForm" size="small" inactive-text="提交后保留表单" />
          </el-col>
          <el-col :span="10" class="cupk2-right">
            <el-button v-if="formCtrl.isShowReset" type="warning" @click="onResetForm">清空</el-button>
            <el-button v-if="formCtrl.isShowSubmit" type="info" plain @click="drawerWinOpen(false)">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script lang="ts" setup>

import { inject, onMounted, reactive, ref } from 'vue';
import v from '@/hook/cupkFormValids';
import cupk2Request from '@/service/remoteRequests/Cupk2Request';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import notice from '@/components/msg/CupkNotice';
import { getCreatType, getUpdateType, getViewType, type FormParam } from '@/types/commons/FormType';
import type { DataResponse } from '@/types/commons/DataResponse';
import type { Emitter, EventType } from 'mitt';
import { PageEvent } from '@/types/commons/PageEvent';
import cupkFormUtils from '@/hook/cupkFormUtils';
const eventBus = inject('eventBus') as Emitter<Record<EventType, unknown>>;
const ruleFormRef = ref()
const isLoading = ref(false);
const isRetainForm = ref(false);
const currentFormType = reactive<FormParam>({ type: getViewType(), id: '', data: {} });


const formCtrl = reactive({
  isShowRetain: true,
  isShowSubmit: true,
  isDrawerOpen: false,
  isAbledForm: false,
  isShowReset: true,
  isShowValidMsg:true,
});


const isShowform = reactive({
  id: true,
  title: true,
  docdescribe: true,
  knowmodel: true,
  author: true,
  pubtime: true,
  source: true,
  state: true,
  ctime: true,
  etime: true,
  cusername: true,
  cuserkey: true,
  eusername: true,
  euserkey: true,
  pcontent: true,
  runinfoid: true,
  syncid: true,
  versionid: true,
  sno: true,
  validitys: true,
  validitye: true,
});


const form = reactive({
  id: '',
  title: '',
  docdescribe: '',
  knowmodel: '',
  author: '',
  pubtime: '',
  source: '',
  state: '',
  ctime: '',
  etime: '',
  cusername: '',
  cuserkey: '',
  eusername: '',
  euserkey: '',
  pcontent: '',
  runinfoid: '',
  syncid: '',
  versionid: '',
  sno: 1,
  validitys: '',
  validitye: '',
})


/**
 * 打开或关闭表单窗口
 * @param isOpen
 * @param formType
 */
const drawerWinOpen = (isOpen: boolean, formParam?: FormParam) => {
  if (!isOpen) {
    formCtrl.isDrawerOpen = isOpen;
  } else {
    if (formParam?.type.key !== currentFormType?.type.key) {
      ruleFormRef.value?.resetFields();
    }
    Object.assign(currentFormType, formParam);
    if (formParam?.type.key == getCreatType().key) {
      initCreatForm(formParam);
    }
    if (formParam?.type.key == getUpdateType().key) {
      initUpdateForm(formParam.id);
    }
    if (formParam?.type.key == getViewType().key) {
      initViewForm(formParam.id);
    }
  }
};

/**
 * 初始化创建窗口
 */
const initCreatForm = (formParam: FormParam) => {
  cupkFormUtils.initFormCtrl(getCreatType(), formCtrl);
  formCtrl.isShowValidMsg=true;
  Object.assign(isShowform, {
    id: true,
    title: true,
    docdescribe: true,
    knowmodel: true,
    author: true,
    pubtime: true,
    source: true,
    state: true,
    ctime: true,
    etime: true,
    cusername: true,
    cuserkey: true,
    eusername: true,
    euserkey: true,
    pcontent: true,
    runinfoid: true,
    syncid: true,
    versionid: true,
    sno: true,
    validitys: true,
    validitye: true,
  });
  if (formParam) {

  }
}

/**
 * 初始化更新窗口
 * @param id
 */
const initUpdateForm = (id: string | undefined) => {
  cupkFormUtils.initFormCtrl(getUpdateType(), formCtrl);
  if (!id) {
    notice.byError("id不能为空");
  } else {
    formCtrl.isShowValidMsg=true;
    viewData(id);
    Object.assign(isShowform, {
        id: true,
        title: true,
        docdescribe: true,
        knowmodel: true,
        author: true,
        pubtime: true,
        source: true,
        state: true,
        ctime: true,
        etime: true,
        cusername: true,
        cuserkey: true,
        eusername: true,
        euserkey: true,
        pcontent: true,
        runinfoid: true,
        syncid: true,
        versionid: true,
        sno: true,
        validitys: true,
        validitye: true,
      });
  }
}

/**
 * 初始化浏览窗口
 * @param id
 */
const initViewForm = (id: string | undefined) => {
  cupkFormUtils.initFormCtrl(getViewType(), formCtrl);
  if (!id) {
    notice.byError("id不能为空");
  } else {
    formCtrl.isShowValidMsg=false;
    viewData(id);
  }
}

/**
 * 展示信息（加载用户信息）
 */
const viewData = async (id: string) => {
  cupk2Request.submit('api/zhzmknow/' + id, RequestTypeEnum.get, isLoading).then((response: DataResponse) => {
    Object.assign(form, response.data)
  }).catch((msg: string) => {
    notice.byError(msg);
  });
}

/**
 * 执行提交按钮（创建/更新）
 */
const addData = async () => {

  if (currentFormType.type.key == getCreatType().key) {
    cupk2Request.submit('api/zhzmknow', RequestTypeEnum.post, isLoading, form).then(() => {
      notice.bySuccess("创建成功!");
      eventBus.emit(PageEvent.data_do_query);
      if (!isRetainForm.value) {
        onResetForm();
        drawerWinOpen(false);
      }
    }).catch((msg: string) => {
      notice.byError(msg);
    });
  }

  if (currentFormType.type.key == getUpdateType().key) {
    cupk2Request.submit('api/zhzmknow/' + form.id, RequestTypeEnum.put, isLoading, form).then(() => {
      notice.bySuccess("更新成功!");
      eventBus.emit(PageEvent.data_do_query);
      onResetForm();
      drawerWinOpen(false);
    }).catch((msg: string) => {
      notice.byError(msg);
    });
  }
}


/**清空表单 */
const onResetForm = () => {
  ruleFormRef.value.resetFields();
}

/**
 * 校验表单，准备提交
 * @param func
 */
const onSubmitForm = async (func: () => void) => {
  await ruleFormRef.value.validate((valid: boolean) => { if (valid) { func() } });
}

onMounted(() => {
  eventBus.on(PageEvent.data_form_open, (paras) => {
    drawerWinOpen((paras as { isOpen: boolean }).isOpen, (paras as { type: FormParam }).type);
  })
});
</script>
